package com.example.chaomi;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.ServiceManager;
import android.os.storage.IMountService;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.util.Log;
import android.widget.Toast;

/**
 * @author Giec:lijh
 *
 */
public class FormatDisk {
	
	private Context mContext;
	private IMountService mMountService;
	private VolumeInfo volumeinfo;
	private List<VolumeInfo> volumeInfos =new ArrayList<>();
	private List<String> mDevices=new ArrayList<>();
	private String path;
	private static final String TAG = "Giec:lijh";
	
	public FormatDisk(Context context){		
		mContext=context;
		getAllDevices();
	}
	/**
	 * get VolumeDescription
	 * @return List<String>
	 */
	public List<String> getVolumeDescription() {
		return mDevices;
	}
	
	/**
	 * getVolumeInfos
	 * @return List<VolumeInfo>
	 */
	public List<VolumeInfo> getVolumeInfos() {
		return volumeInfos;
	}	
	
	/**
	 * format given Volume
	 * @param info VolumeInfo
	 */
	public void format(VolumeInfo info) {
		this.volumeinfo=info;
		path=volumeinfo.path;
		StorageManager	mStorage = mContext.getSystemService(StorageManager.class);
		new PartitionTask(mStorage,volumeinfo).execute(null,null,null);
	}
	
	private List<String> getAllDevices(){
		StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
		List<VolumeInfo> allvolumeInfos = sm.getVolumes();
        if (allvolumeInfos==null||allvolumeInfos.size()<=0)
        	return null;       
        for(VolumeInfo volumeInfo :allvolumeInfos){
        	 if(volumeInfo.type==VolumeInfo.TYPE_PUBLIC
                     && (volumeInfo.state==VolumeInfo.STATE_MOUNTED 
                     || volumeInfo.state==VolumeInfo.STATE_MOUNTED_READ_ONLY)){
        		 
            mDevices.add(sm.getBestVolumeDescription(volumeInfo));
    	    volumeInfos.add(volumeInfo);
    	}else{
    		continue;
    	}
        }
        return mDevices;
	}
	class PartitionTask extends AsyncTask<Void, Integer, Exception> {      

        private volatile int mProgress = 20;
        private StorageManager storage;
        VolumeInfo mDisk;
        
        public PartitionTask(StorageManager storage,VolumeInfo mDisk){
        	this.storage=storage;
        	this.mDisk=mDisk;
        }
        @Override
        protected Exception doInBackground(Void... params) {           

        	return formatMedia(path);
            }      

        @Override
        protected void onProgressUpdate(Integer... progress) {
            mProgress = progress[0];
            
        }       
        @Override
        protected void onPostExecute(Exception e) {
        	if(e!=null)
        		Toast.makeText(mContext, "e= "+e.toString()+"   finish", Toast.LENGTH_LONG).show();
        	else
        		Toast.makeText(mContext,"format success", Toast.LENGTH_SHORT).show();
           
        }
    }
	 private Exception formatMedia(final String path) {
	        IMountService mountService =  getMountService();
	        int result = -1;
	        try {
	            mountService.unmountVolume(path, true, false);
	            Thread.sleep(4 * 1000);
	            result = mountService.formatVolume(path); 
	            if (result == 0) {
	                Thread.sleep(4 * 1000);
	                int resultMount = mountService.mountVolume(path); //挂载回去
		            Log.d(TAG, "---------volume's path is " + path + "------format success");
	                Log.d(TAG, "---------result_mount " + resultMount); //挂载结果
	            }
	            if(result!=0)
	            	return new RuntimeException();
	            return null;
	        } catch (Exception ex) {
	            ex.printStackTrace();
	            return ex;
	        }
	        
	    }
	 private synchronized IMountService getMountService() {
	        if (mMountService == null) {
	            IBinder iBinder = ServiceManager.getService("mount");
	            if (iBinder != null) {
	                 mMountService = IMountService.Stub.asInterface(iBinder);
	                if (mMountService == null) {
	                    Log.e("11111", "Unable to connect to mount service! - is it running yet?");
	                }
	            }
	        }
	        return mMountService;
	}
}
